package com.ma.chapter6.unsafe;

import lombok.Data;
import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class TestUnsafe {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        /*
         * Unsafe 对象提供了非常底层的，操作内存、线程的方法，Unsafe 对象不能直接调用，只能通过反射获得
         * */
        Unsafe unsafe = UnsafeAccessor.getUnsafe();

        ////通过反射拿到Unsafe类的私有字段
        //Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        ////设置允许访问私有成员变量
        //theUnsafe.setAccessible(true);
        ////拿到该静态成员变量
        //Unsafe unsafe = (Unsafe) theUnsafe.get(null);


        /* Unsafe CAS 操作 */
        Field id = Student.class.getDeclaredField("id");
        Field name = Student.class.getDeclaredField("name");

        //1、获得成员变量/域/属性的偏移量
        long idOffset = unsafe.objectFieldOffset(id);
        long nameOffset = unsafe.objectFieldOffset(name);
        Student student = new Student();

        //2、使用CAS方法替换成员变量的值
        unsafe.compareAndSwapInt(student,idOffset,0,20);
        unsafe.compareAndSwapObject(student,nameOffset,null,"张三");

        System.out.println(student);


    }
}

@Data
class Student {
    volatile int id;
    volatile String name;
}
